package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    @Autowired
    private DeptService deptService;

    //进入部门管理页面
    @RequestMapping(value = "/list" ,name = "进入部门管理页面")
    public String findAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<Dept> pageInfo = deptService.findPage(getCompanyId(),page,pageSize);
        request.setAttribute("page",pageInfo);
        return "system/dept/dept-list";
    }

    //进入部门新增
    @RequestMapping(value = "/toAdd",name = "进入部门新增页面")
    public String toAdd(){
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    //保存部门
    @RequestMapping(value ="/edit",name = "保存部门方法")
    public String edit(Dept dept){
        //判断上级部门是否为无
        if ("".equals(dept.getParent().getId())){
            dept.getParent().setId(null);
        }

        //dept的id为空就是新增,否则修改
        if (StringUtils.isEmpty(dept.getId())){
            //设置公司id和名称
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());

            //id赋值一个随机id
            dept.setId(UUID.randomUUID().toString());
            deptService.save(dept);
        }else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    //进入部门修改页面
    @RequestMapping(value = "/toUpdate",name = "进入修改部门页面")
    public String toUpdate(String id){
        //根据id查询部门
        Dept dept = deptService.findById(id);
        //放到request域中,用作数据回显
        request.setAttribute("dept",dept);

        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
       //修改页面和新增页面公用一套
        return "system/dept/dept-add";
    }

    //删除部门
    @RequestMapping(value = "/delete",name = "删除部门方法")
    public String delete(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }

}
